package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.ExercisesetandquestionQueryCriteria;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.service.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;

@RestController
@RequiredArgsConstructor
@Api(tags = "任务试题集记录")
@RequestMapping("/api/teskExerciseSetRecord")
public class TeskExerciseSetRecordController {

    private final TeskExerciseSetRecordService teskExerciseSetRecordService;

    private final TeskExerciseSetCompleteService teskExerciseSetCompleteService;

    private final QuestionoptionService questionoptionService;

    private final QuestionService questionService;

    private final ExercisesetandquestionService exercisesetandquestionService;

    private final UserMapper userMapper;

    private final UserService userService;
    @PostMapping
    @Log("新增试题答题记录")
    @ApiOperation("新增试题答题记录")
    public ResponseEntity<Object> createUserquestionlog(@RequestBody TeskExerciseSetRecord resources){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();

        if(resources.getTeskId()!=null){
            queryWrapper.eq("teskId",resources.getTeskId());
        }

        if(resources.getExerciseSetId()!=null){

            queryWrapper.eq("exerciseSetId",resources.getExerciseSetId());

        }
        if(resources.getExerciseSetId()!=null){

            queryWrapper.eq("userId",currentUser.getId());

        }


        TeskExerciseSetComplete teskExerciseSetComplete = teskExerciseSetCompleteService.getOne(queryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
//        String timestamp = sdf.format(new Date());
        if(teskExerciseSetComplete!=null && teskExerciseSetComplete.getId()!=null){
            if(Objects.equals(teskExerciseSetComplete.getState(), "1")){
                return new ResponseEntity<>("该试卷已提交", HttpStatus.OK);
            }

        } else {
            TeskExerciseSetComplete teskExerciseSetComplete1 = new TeskExerciseSetComplete();
            teskExerciseSetComplete1.setExerciseSetId(resources.getExerciseSetId());
            if(currentUser!=null && currentUser.getId()!=null){
                teskExerciseSetComplete1.setUserId(Math.toIntExact(currentUser.getId()));

            }
            teskExerciseSetComplete1.setTeskId(resources.getTeskId());
            teskExerciseSetComplete1.setState(0);

            teskExerciseSetCompleteService.save(teskExerciseSetComplete1);

        }

        //判断是否正确
        QueryWrapper optionQueryWrapper = new QueryWrapper<>();
        optionQueryWrapper.ge("questionId",resources.getQuestionId());
        List<Questionoption> questionoptionList =  questionoptionService.list(optionQueryWrapper);

        if(resources.getQuestionType() !=null && resources.getQuestionType() == 0){//单选 && 判断
            resources.setIsTrue(0);
            for(Questionoption questionoption:questionoptionList){
                if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(resources.getContent()))){
                    resources.setIsTrue(1);
                }
            }

        } else if(resources.getQuestionType() !=null && resources.getQuestionType() == 1){//多选

            List<Integer> contents = new ArrayList<>();
            if(!resources.getContent().isEmpty()){
                contents = JSON.parseObject(resources.getContent(), (Type) List.class);
            }
            List<Integer> result = new ArrayList<>();
            List<String> result2 = new ArrayList<>();
            for(Questionoption questionoption:questionoptionList){
                for(Integer content: contents){
                    if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(content)) && questionoption.getIsTrue() == 1){
                        result.add(content);
                    }
                }
                if(questionoption!=null && questionoption.getIsTrue() !=null && questionoption.getIsTrue() == 1){
                    result2.add(String.valueOf(questionoption.getId()));
                }
            }
            if(result2.size() == result.size()){
                resources.setIsTrue(1);
            } else {
                resources.setIsTrue(0);
            }
        }else if(resources.getQuestionType() !=null && resources.getQuestionType() == 2){//判断
            resources.setIsTrue(0);
            for(Questionoption questionoption:questionoptionList){

                if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(resources.getContent())) && questionoption.getIsTrue() == 1){
                    resources.setIsTrue(1);
                }
            }
        } else if(resources.getQuestionType() !=null && resources.getQuestionType() == 3){//填空


            if(!resources.getContent().isEmpty()){
                List<String> contents = null;
                contents = JSON.parseObject(resources.getContent(), (Type) List.class);

                QueryWrapper queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("id",resources.getQuestionId());
                Question question = questionService.getOne(queryWrapper2);
                if(question.getIsTurnFill()!=null && question.getIsTurnFill() == 1){
                    resources.setIsTrue(0);
                    List<String> finalContents = contents;
                    IntStream.range(0,contents.size()).forEach(item1 -> {
                        IntStream.range(0,questionoptionList.size()).forEach(item2 -> {
                            if(item1 == item2){
                                if(finalContents.get(item1) == questionoptionList.get(item2).getName()){
                                    resources.setIsTrue(1);
                                }
                            }
                        });

                    });

                } else {

                    resources.setIsTrue(0);
                    for(Questionoption questionoption:questionoptionList){
                        for(String content: contents){
                            if(Objects.equals(String.valueOf(questionoption.getName()), content)){
                                resources.setIsTrue(1);
                            }
                        }
                    }

                }
            }


        }


        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("exerciseSetId",resources.getExerciseSetId());
        queryWrapper2.eq("questionId",resources.getQuestionId());
        Exercisesetandquestion exercisesetandquestion = exercisesetandquestionService.getOne(queryWrapper2);

        if(resources.getIsTrue()!=null && resources.getIsTrue() == 1){
            resources.setScore(exercisesetandquestion.getScore());
        } else {
            resources.setScore("0");
        }



        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("exerciseSetId", resources.getExerciseSetId());
        queryWrapper1.eq("questionId", resources.getQuestionId());
        queryWrapper1.eq("teskId", resources.getTeskId());
        queryWrapper1.eq("userId", currentUser.getId());
        TeskExerciseSetRecord teskExerciseSetRecord = teskExerciseSetRecordService.getOne(queryWrapper1);

        System.out.println("teskExerciseSetRecord"+teskExerciseSetRecord);
        resources.setUserId(Math.toIntExact(currentUser.getId()));
        if(teskExerciseSetRecord!=null){

            resources.setId(teskExerciseSetRecord.getId());
            teskExerciseSetRecordService.update(resources,queryWrapper1);
        } else {
            teskExerciseSetRecordService.save(resources);
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping
    @Log("查询任务题库试题")
    @ApiOperation("查询任务题库试题")
//    @PreAuthorize("@el.check('exercisesetandquestion:list')")
    public ResponseEntity<List<Question>> queryExercisesetandquestion(@Param("criteria") TeskExerciseSetRecord criteria){

        TeskExerciseSetComplete teskExerciseSetComplete = new TeskExerciseSetComplete();
        //获取本试卷状态
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userService.getOne(new QueryWrapper<User>().eq("username", currentUserName));
        QueryWrapper userExercisetqueryWrapper = new QueryWrapper<>();

        userExercisetqueryWrapper.eq("teskId",criteria.getTeskId());


        if(criteria.getExerciseSetId()!=null){

            userExercisetqueryWrapper.eq("exerciseSetId",criteria.getExerciseSetId());

        }

        if(currentUser.getId()!=null){
            userExercisetqueryWrapper.eq("userId",currentUser.getId());
            teskExerciseSetComplete = teskExerciseSetCompleteService.getOne(userExercisetqueryWrapper);
        }
        ExercisesetandquestionQueryCriteria criteria1 = new ExercisesetandquestionQueryCriteria();
        criteria1.setExercisesetId(criteria.getExerciseSetId());
        //获取试题列表
        List<Exercisesetandquestion> list1 = exercisesetandquestionService.queryAll(criteria1);

        List<Integer> list2 = new ArrayList<>();
        for(Exercisesetandquestion existetandquestion :list1){
            list2.add(existetandquestion.getQuestionid());
        }

        List<Question> questionList = questionService.queryAllByIds(list2);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("questionId",list2);
        List<Questionoption> questionOptionList =  questionoptionService.list(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("questionId",list2);
        queryWrapper1.in("userId",currentUser.getId());
        queryWrapper1.in("teskId",criteria.getTeskId());

        List<TeskExerciseSetRecord> userquestionlogs =  teskExerciseSetRecordService.list(queryWrapper1);
        for(Question question : questionList){
            List<Questionoption> questionoptions = new ArrayList<>();
            List<TeskExerciseSetRecord> userquestionlog1s = new ArrayList<>();

            for(Questionoption questionoption:questionOptionList){
                if(Objects.equals(question.getId(), questionoption.getQuestionid())){
                    if(teskExerciseSetComplete!=null && !Objects.equals(teskExerciseSetComplete.getState(), "1")) {
                        questionoption.setIsTrue(null);
                    }
                    if(question.getType() == 3){
                        if(teskExerciseSetComplete!=null && !Objects.equals(teskExerciseSetComplete.getState(), "1")) {
                            questionoption.setName(null);
                        }
                        questionoptions.add(questionoption);
                    } else {
                        questionoptions.add(questionoption);
                    }

                }
            }

            for(TeskExerciseSetRecord userquestionlog :userquestionlogs){
                if(Objects.equals(String.valueOf(question.getId()), String.valueOf(userquestionlog.getQuestionId()))){

                    userquestionlog1s.add(userquestionlog);
                }
            }

            question.setQuestionoptions(questionoptions);


            question.setTeskExerciseSetRecord(userquestionlog1s);
            if(userquestionlog1s.size() != 0){
                question.setAnswerArr(userquestionlog1s.get(0).getContent());
            }



        }
        return new ResponseEntity<>(questionList,HttpStatus.OK);
    }
}
